package com.zywl.api;

import com.zywl.utils.models.JsonResult;
import com.zywl.utils.utils.Constants;
import com.zywl.utils.utils.FileUtil;
import com.zywl.web.controller.base.BaseController;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/upload/")
public class UploadApi extends BaseController {


    /**
     * 上传照片
     * @param request
     * @param multipartRequest
     * @return
     */
    @ResponseBody
    @RequestMapping("uploadfile")
    public JsonResult uploadfile(HttpServletRequest request, DefaultMultipartHttpServletRequest multipartRequest, String type){
        JsonResult jr = new JsonResult();
        try {
            CommonsMultipartFile file = (CommonsMultipartFile)multipartRequest.getFile("file");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            StringBuffer stringBuffer=new StringBuffer();
            stringBuffer.append(Constants.STRING_SPRIT);
            stringBuffer.append("static");
            stringBuffer.append(Constants.STRING_SPRIT);
            stringBuffer.append("file");
            if(StringUtils.isNotEmpty(type)){
                stringBuffer.append(Constants.STRING_SPRIT);
                stringBuffer.append(type);
            }
            stringBuffer.append(Constants.STRING_SPRIT);
            stringBuffer.append(sdf.format(new Date()));
            stringBuffer.append(Constants.STRING_SPRIT);
            stringBuffer.append(System.currentTimeMillis());
            stringBuffer.append(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")));

            StringBuffer sb=new StringBuffer();
//            sb.append("decoration");
            sb.append(stringBuffer.toString());

            String filePath = FileUtil.getFileRealPathForServer(request, sb.toString());
            File newFile = FileUtil.newFile(filePath);
            file.transferTo(newFile);

            Map<String,String> pathMap = new HashMap<>();
            pathMap.put("path",stringBuffer.toString());
            pathMap.put("fullpath", Constants.DOMAIN + stringBuffer.toString());
            jr.success("上传文件成功",pathMap);
        } catch (Exception e) {
            logger.error("上传文件失败",e);
            jr.error("上传文件失败");
        }
        return jr;
    }
}
